#include "object.h"


// 在链表中找到指定id的对象
StratumObject* objectFind(CommonList* list, int id, bool lock) {
    if (lock) {
        list->enter();
    }

    for (PCLI li = list->m_first; li; li = li->next) {
        StratumObject* obj = (StratumObject*)li->data;
        if (obj->m_id == id) {
            if (lock) {
                objectLock(obj);
                list->leave();
            }
            return obj;
        }
    }

    if (lock) {
        list->leave();
    }

    return nullptr;
}

// 剪枝
void objectPrune(CommonList* list, StratumObjectDeleteFunc deleteFunc) {
    list->enter();
    for (PCLI li = list->m_first; li && list->m_count > 0; ) {
        PCLI toDel = li;
        StratumObject* obj = (StratumObject*)li->data;
        li = li->next;

        if (!obj) {
            continue;
        }
        // 1.已被标记为删除,也没有任何人锁定,直接删除
        if (obj->m_deleted && !obj->m_lock_count) {
            deleteFunc(obj);
            toDel->data = nullptr;
            list->del(toDel);
        }
        // 2.有人锁定，但是标记为未锁
        else if (obj->m_lock_count && obj->m_unlock) {
            obj->m_lock_count--;
        }
    }
    if (list->m_count) {
        printf("still %d objects in list\n", list->m_count);
    }

    list->leave();
}


// 加锁对象
void objectLock(StratumObject* obj) {
    if (!obj) {
        return ;
    }
    obj->m_lock_count++;
}

// 解锁对象
void objectUnlock(StratumObject* obj) {
    if (!obj) {
        return;
    }
    obj->m_lock_count--;
}

// 删除对象
void objectDelete(StratumObject* obj) {
    if (!obj) {
        return ;
    }
    obj->m_deleted = true;
}